<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateUserTicketModelAPIRequest;
use App\Http\Requests\API\UpdateUserTicketModelAPIRequest;
use App\Http\Services\UserTicketDTOBuilderService;
use App\Models\UserTicketModel;
use App\Repositories\UserTicketRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Illuminate\Http\Response;

/**
 * Class UserTicketModelController
 * @package App\Http\Controllers\API
 */

class UserTicketController extends AppBaseController
{
    /** @var  UserTicketRepository */
    private $userTicketModelRepository;

    /**
     * 查询用户的代金券
     * @param UserTicketRepository $repo
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiSearch(UserTicketRepository $repo)
    {
        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();

        $searchOptions['user_id'] = $this->request->attributes->get('user_id');
        $searchOptions['category_id'] = $this->request->get('category_id', 0);
        if (empty($searchOptions['category_id'])) {
            unset($searchOptions['category_id']);
        }
        $ret = $repo->search($searchOptions, $sortOptions);
        if (empty($ret['lists'])) {
            return $this->success(['lists' => []]);
        }
        $ret['lists'] = UserTicketDTOBuilderService::buildTickets($this->request->attributes->get('user_id'), $ret['lists']);

        return $this->success($ret);
    }

    /**
     * 查询用户的代金券
     * @param UserTicketRepository $repo
     * @return \Illuminate\Http\JsonResponsec
     */
    public function backstageSearch(UserTicketRepository $repo)
    {
        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();

        $searchOptions['money'] = $this->request->get('money', 0);
        $searchOptions['category_id'] = $this->request->get('category_id', 0);
        if (empty($searchOptions['category_id'])) {
            unset($searchOptions['category_id']);
        }

        if (empty($searchOptions['money'])) {
            unset($searchOptions['money']);
        }

        $ret = $repo->backstageSearch($searchOptions, $sortOptions);
        if (empty($ret['lists'])) {
            return $this->success(['lists' => []]);
        }
        $ret['lists'] = UserTicketDTOBuilderService::buildTickets(0, $ret['lists']);

        return $this->success($ret);
    }

    /**
     * 查询用户的代金券
     * @param UserTicketRepository $repo
     * @return \Illuminate\Http\JsonResponse
     */
    public function search2($userId, UserTicketRepository $repo)
    {
        $input = $this->request->all();

        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();
        $cityId = array_get($input, 'city_id', 0);
        !empty($cityId) && $searchOptions['city_id'] = $cityId;
        $cateogyId = array_get($input, 'category_id', 0);
        !empty($cateogyId) && $searchOptions['category_id'] = $cateogyId;

        $searchOptions['user_id'] = $userId;
        $ret = $repo->search($searchOptions, $sortOptions);
        if (empty($ret['lists'])) {
            return $this->success(['lists' => []]);
        }
        $ret['lists'] = UserTicketDTOBuilderService::buildTickets($userId, $ret['lists']);

        return $this->success($ret);
    }

    /**
     * Store a newly created UserTicketModel in storage.
     * POST /userTicketModels
     *
     * @param CreateUserTicketModelAPIRequest $request
     *
     * @return Response
     */
    public function store(UserTicketRepository $repository)
    {
        $input = $this->request->all();
        $this->validateInputParams('store', $input);

        $input['user_id'] = $this->request->attributes->get('user_id');
        $userTicketModels = $repository->create($input);
        return $this->sendResponse($userTicketModels->toArray(), 'ok');
    }

    /**
     * Display the specified UserTicketModel.
     * GET|HEAD /userTicketModels/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id, UserTicketRepository $userTicketRepository)
    {
        /** @var UserTicketModel $userTicketModel */
        $userTicketModel = $userTicketRepository->findWithoutFail($id);

        if (empty($userTicketModel)) {
            return $this->sendError('User Ticket Model not found');
        }

        return $this->sendResponse($userTicketModel->toArray(), 'User Ticket Model retrieved successfully');
    }

    /**
     * Update the specified UserTicketModel in storage.
     * PUT/PATCH /userTicketModels/{id}
     *
     * @param  int $id
     * @param UpdateUserTicketModelAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateUserTicketModelAPIRequest $request)
    {
        $input = $request->all();

        /** @var UserTicketModel $userTicketModel */
        $userTicketModel = $this->userTicketModelRepository->findWithoutFail($id);

        if (empty($userTicketModel)) {
            return $this->sendError('User Ticket Model not found');
        }

        $userTicketModel = $this->userTicketModelRepository->update($input, $id);

        return $this->sendResponse($userTicketModel->toArray(), 'UserTicketModel updated successfully');
    }

    /**
     * export 导出excel
     * @param UserTicketRepository $repo
     */
    public function export(UserTicketRepository $repo)
    {
        $str = '';
        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();
        $sortOptions['all'] = 1;

        $searchOptions['status'] = [0, 1];
        $input = $this->request->all();
        $type = array_get($input, 'type', 0);
        !empty($type) && $searchOptions['type'] = $type;

        $ret = $repo->search($searchOptions, $sortOptions);

        $lists = $ret['lists'];
        if (count($lists) == 0) {
            return $this->error(1, "无数据,无需导出");
        }

        $filename = '/storage/ticket.xlsx';

        $url = UserTicketDTOBuilderService::export($lists, $filename);

        return response($url)->header('Content-Type', 'text/html');
    }

    /**
     * Remove the specified AdminModel from storage.
     * DELETE /adminModels/{id}
     *
     * @param  int $idbatch
     *
     */
    public function batchDestroy()
    {
        $ids = $this->request->get('ids');
        if (empty($ids)) {
            return $this->sendError('id不为空');
        }

        $ids = explode(',', $ids);
        // 删除ticket
        UserTicketModel::whereIn('id', $ids)->update(['status' => 2]);

        return $this->success([], '操作成功');
    }

    /**
     * Remove the specified UserTicketModel from storage.
     * DELETE /userTicketModels/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id, UserTicketRepository $repository)
    {
        /** @var UserTicketModel $userTicketModel */
        $userTicketModel = $repository->findWithoutFail($id);

        if (empty($userTicketModel)) {
            return $this->sendError('User Ticket Model not found');
        }

        $userTicketModel->delete();

        return $this->sendResponse($id, 'User Ticket Model deleted successfully');
    }

    /**
     * 参数验证规则
     * self::VALID_RULES[__FUNCTION__]
     */
    const VALID_RULES = [
        'store' => [
            'category_id' => 'required|int',
            'bank_name' => 'required|string',
            'bank_code' => 'required|string',
            'tax_id' => 'sometimes|string',
            'email' => 'sometimes|string|email',
            'mobile' => 'sometimes|string|string',
            'name' => 'sometimes|string',
            'address' => 'sometimes|string',
            'title' => 'sometimes|string',
            'ticket_type' => 'sometimes|int',
            'money' => 'required|numeric',
            'title_category' => 'sometimes|int|min:1|max:2',
        ],
        'update' => [
            'category_id' => 'int|min:1',
            'bank_name' => 'string',
            'bank_code' => 'string',
            'tax_id' => 'string',
            'email' => 'sometimes|string|email',
            'name' => 'string',
            'title' => 'string',
            'money' => 'numeric',
            'mobile' => 'sometimes|string|string',
            'status' => 'int|min:1',
            'title_category' => 'sometimes|int',
            'title_type' => 'sometimes|int',
            'address' => 'sometimes|string',
        ],
    ];
}
